package in.unlocker.apps.unlock.web.registration;

import in.unlocker.apps.unlock.dao.MasterDataRepository;
import in.unlocker.apps.unlock.dao.UserRepository;
import in.unlocker.apps.unlock.model.registration.User;
import in.unlocker.apps.unlock.service.UserService;
import in.unlocker.apps.unlock.service.exception.ApplicationException;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@Secured("ROLE_ANONYMOUS")
public class RegistrationController
{

	Log log = LogFactory.getLog(RegistrationController.class);

	@Autowired
	private UserService userService;

	@Autowired
	protected MasterDataRepository masterDataRepository;

	@Autowired
	private UserRepository userRepository;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response)
	{
		log.debug("within login GET method call");

		return "register/login";
	}

	@RequestMapping(value = "/register/{id}", method = RequestMethod.GET)
	public String index(@ModelAttribute(value = "user") User user, BindingResult errors, HttpServletRequest request,
			HttpServletResponse response, @PathVariable Integer id)
	{

		return null;
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(@ModelAttribute(value = "user") User bean, BindingResult errors, HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		return null;
	}

	@RequestMapping(value = "/register/registerProfile", method = RequestMethod.POST)
	public String registerProfile(@ModelAttribute(value = "user") User user, @RequestParam("file") MultipartFile file,
			BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return null;
	}

	private void uploadProfileImage(Integer profileId, MultipartFile file) throws ApplicationException
	{
		if (!file.isEmpty())
		{

			try
			{
				userService.saveProfilePhoto(profileId, file.getBytes());
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// Save the id you have used to create the file name in the DB. You
			// can retrieve the image in future with the ID.
		}
		else
		{
			throw new ApplicationException("Invalid profile photo");
		}

	}

	@RequestMapping(value = "register/verify", method = RequestMethod.GET)
	public String verifyEmail(@ModelAttribute(value = "user") User bean, HttpServletRequest request,
			HttpServletResponse response)
	{
		return null;
	}

	@RequestMapping(value = "/register/uploadProfileImage", method = RequestMethod.POST)
	public String handleFormUpload(@RequestParam("file") MultipartFile file) throws IOException
	{
		if (!file.isEmpty())
		{
			BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
			File destination = new File("File directory with file name"); // something
																			// like
																			// C:/Users/tom/Documents/nameBasedOnSomeId.png
			ImageIO.write(src, "png", destination);
			// Save the id you have used to create the file name in the DB. You
			// can retrieve the image in future with the ID.
		}
		String ret = null;// "redirect:/register/"+bean.getProfile().getId();
		return ret;
	}

	@RequestMapping(value = { "/user/profile/{profileId}" }, method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
	public @ResponseBody
	byte[] downloadFile(@PathVariable Integer profileId, HttpServletRequest request, HttpServletResponse response)
	{
		return userService.getProfileImage(profileId);
	}

	@RequestMapping(value = "/forgotpassword", method = RequestMethod.GET)
	public String forgotPassword(@ModelAttribute(value = "user") User bean, BindingResult errors,
			HttpServletRequest request, HttpServletResponse response)
	{

		return "register/forgotpassword";
	}

	// TODO remove the user bean since we just need the email id. same is applicable for OCMS also
	@RequestMapping(value = "/forgotpassword", method = RequestMethod.POST)
	public String submitForgotPassword(@ModelAttribute(value = "user") User bean, BindingResult errors,
			HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			userService.forgotPassword(request.getParameter("emailId"));
		}
		catch (Exception e)
		{

			// ae.getCause() == null?
			// ae.getMessage():ae.getCause().getMessage())
			errors.addError(new ObjectError("registration.forgotpassword.error", "Unable to fetch password : "
					+ e.getMessage()));
			return "register/forgotpassword";
		}
		request.setAttribute("result", "user.forgotpassword.success");
		return "common/success";
	}

}
